<!--聊天私聊某人的界面!-->
<template>
    <div class="chart_container">
        <!-- 聊天头 -->
        <van-nav-bar :title="chatObj.name" class="header" left-text="" left-arrow @click-left="backToAddress()">
        </van-nav-bar>
        <div style="display: flex;flex-direction: row;flex: 1;overflow: auto;">
            <div class="chatcontentbox" ref="messagebox">
                <!-- {{chatObj}} -->
                <!-- 顶部下拉部分 -->
                <!-- {{messagelist}} -->
                <!-- receiveid -->
                <!-- {{responseTime}} -->
                <!-- JSON处理的接收到的消息类型：{{JSON.stringify(resciveMsg).type}}<br> -->
                <!-- 最后的消息列表：{{messagelist}}<br> -->
                <!-- {{chatObj}} -->
                <div style="position: absolute;top: 0;z-index: 9;width: 100%;height: 1rem;">
                    <van-pull-refresh style="height: 100%" v-model="isLoading" @refresh="onRefresh">
                    </van-pull-refresh>
                </div>
                <!--                    {{ responseTime }}-->
                <Messageitem v-for="(item, index) in messagelist" :key="index" :dt="item" :list="messagelist"
                    :preindex="index" :objName="chatObj.name" />
            </div>
            <div class="right" v-if="isShowMap">
                <Map />
            </div>
        </div>
        <!-- 底部输入区域 -->
        <div class="chatinpubox">
            <div class="inputpart">
                <!-- 语音切换开关-->
                <!-- <div class="soundbtnbox">
                                <img
                                        v-show="!soundinput"
                                        @click="soundinput = !soundinput"
                                        class="iconBtn"
                                        src="img/iconfont/sound.png"
                                />
                                <img
                                        v-show="soundinput"
                                        @click="soundinput = !soundinput"
                                        class="iconBtn"
                                        src="img/iconfont/noSound.png"
                                />
                            </div> -->
                <!-- input  -->
                <div class="inputsoundmsg" @touchstart="lpstart()" @touchend="lpend()" v-show="soundinput">
                    按住说话
                </div>
                <input class="inputmsg" type="text" v-model="message" v-show="!soundinput" placeholder="请输入要发送的内容" />
                <!-- + 下拉按钮 -->
                <!-- <div style="margin: 0 0.1rem;">
                                <img class="iconBtn" @click="showsubbtnbox" src="img/iconfont/pluscircle.png" alt />
                            </div> -->
                <!-- 发送按钮 -->
                <div class="send_btn" @click="sendmsg"></div>

            </div>


            <!-- resciveMsg：{{resciveMsg}} -->
        </div>
    </div>
</template>
<script>

import { getHistoryChats, sendMessage } from "@/request/api.js"
import { formatTimeToStr } from "@/utils/date.js"

import Messageitem from "./Message.vue";
import Map from '../../views/Navigation.vue';
import LeafletMap from '../../views/LeafletMap.vue';
import bus from "./../../utils/bus";
import { Toast } from "vant";

import timecal from "./../../utils/timecal";


export default {
    components: {
        Messageitem,
    },
    props: {
        socketMes: { type: String }
    },
    data() {
        return {
            count: 0,
            isLoading: false,
            //消息
            message: "",
            sendType: "文字",
            chatObj: {
                name: "",
                id: "",
            },
            soundinput: false,
            ee: "",
            //接收到的消息
            resciveMsg: "",
            //消息
            otherbtnsshow: false,
            otherbtnlist: [
                { url: "img/icon/assemblesite.png", title: "图片" },
                { url: "img/icon/dispersesite.png", title: "拍照" },
                { url: "img/icon/destination.png", title: "定位" },
                // { url: 'img/icon/taskobj.png', title: '语音识别' },
            ],

            messagelist: [],
            newSound: false,
            newPic: false,
            test: 0,

            //接收响应的时间
            responseTime: "",

            //聊天对象名
            objName: "",

            imgTest: "",

            //当前的路由
            currentRouter: "",

            //聊天对象
            // objInfo:"",

            // 图片路径
            imgPath: "",

            isShowUpSetting: false, //位置上报设置弹框标识
            carIdNum: "",
            period: "60",
            frePointNum: "4", //频点
            ruzhanFlag: "1", //入站速率
            jinjiFlag: "2", //紧急标识
            iscontinue: true,
            isShowMap: false,
            websocket: null,
        };
    },
    methods: {

        getDtfromRoute() {
            if (this.$route.query !== null) {
                this.chatObj.id = this.$route.query.id;
                this.chatObj.name = this.$route.query.name;
                this.gethistorylist();
            }
        },
        showsubbtnbox() {
            this.otherbtnsshow = !this.otherbtnsshow;
        },
        gethistorylist() {
            let res = $App.getChatHisByPage(
                JSON.stringify({
                    id: this.chatObj.id,
                    page: 1,
                    size: 20,
                })
            );

            this.messagelist = JSON.parse(res).reverse();
            console.log(this.messagelist)

            // getHistoryChats({bdid: this.$systemMes.loginId,limit:60 }).then(res => {
            //     if (res.data != null) {
            //         console.log(res.data.rows)
            //         // console.log( this.messagelist)
            //         this.messagelist = res.data.rows.reverse();
            //         // console.log("聊天数据为；"+JSON.stringify(this.messagelist));
            //         // console.log( res.data.rows.reverse())
            //         // console.log( this.messagelist)
            //         // 控制显示的
            //         this.messagelist.forEach((item, index) => {
            //             if (item.type == "图片") {
            //                 var androidImgKey = "http://androidimg";
            //                 item.content = androidImgKey + item.content;
            //             }
            //             item.content = item.nr;
            //             item.time = item.sj;
            //             if (item.fsztmc === this.chatObj.name) {
            //                 item.receiveid = "local";
            //             }
            //             if (item.nrlx == 2) {
            //                 item.type = "任务";
            //             } else if (item.nrlx == 1) {
            //                 item.type = "高分"
            //             } else {
            //                 item.type = "文字";
            //             }
            //             if (item.jsbdid == this.$systemMes.loginId) {
            //                 item.receiveid = 'local'
            //             }
            //         });
            //     }
            // }).catch(e => {
            //     console.log(e);
            // });


        },
        //语音输入相关
        lpstart() {
            Toast.success("说话中~~~");
            $App.recordVoiceStart(); //开始录音
        },
        lpend() {
            Toast.success("结束~~~");
            $App.recordVoiceEnd(); //结束录音
        },
        showStart() {
            Toast.success("语音识别中~~~");
            this.str = ["请", "到", "528", "厂", "集", "合"];
            this.sendType = "文字";
            let i = 0;
            setInterval(() => {
                if (i < 6) {
                    this.message = this.message + this.str[i];
                    i++;
                }
            }, 500);
        },
        showEnd() {
            Toast.success("语音识别结束~~~");
        },
        recordStart(dt) {
        },
        recordEnd(dt) {
            //安卓提供的音频信息
            this.message = dt;
            this.sendType = "语音";
            this.sendmsg();
        },
        //子点击效果
        subfunc(dt) {
            switch (dt.title) {
                case "图片":
                    this.fun0();
                    break;
                case "拍照":
                    this.fun1();
                    break;
                case "定位":
                    this.fun2();
                    break;
            }
        },
        //图片
        fun0() {
            $App.selectPhoto();
        },
        //拍照
        fun1() {
            let res = $App.takePhoto();
        },
        //定位
        fun2() {
            this.message = "经度:118.767413,纬度:32.04154";
            this.sendType = "文字";

            this.sendmsg();
        },
        //名片
        fun3() {
            Toast.success("暂时没有此功能");
        },
        photoUpload(dt) {
            this.sendType = "图片";
            this.imgPath = dt;
            // console.log("dt",dt);
            if (dt.substring(dt.length - 4) == ".jpg") {
                this.message = dt;
                this.sendmsg();
            } else {
                Toast.fail("请选择jpg格式的文件");
            }
        },
        backToPrev() {
            this.currentRouter = this.$route.path;
            if (this.currentRouter != "/") {
                this.$router.go(-1);
                return 0;
            } else {
                return 1;
            }
        },
        //发送消息
        sendmsg() {
            if (this.soundinput === false && this.sendType !== "图片") {
                this.sendType = "文字";
            }
            if (this.message !== "") {
                let msgbody = {
                    receiveid: this.chatObj.id,
                    type: this.sendType, //'图片'、'文字'、'语音'
                    content: this.message,
                };
                this.ee = msgbody;
                let res = $App.sendChat(JSON.stringify(msgbody)); //返回一个时间
                msgbody.time = res;

                //发送短报文
                // sendMessage({
                //     "fsbdid": this.$systemMes.loginId,
                //     "fsztmc": this.$systemMes.loginName,
                //     "nr": this.message,
                //     "nrlx": 0
                // }).then(res => {
                //     console.log("发送成功");
                // }).catch(e => {
                //     console.log("发送失败")
                // });
                // this.responseTime = new Date();
                // msgbody.time = formatTimeToStr("yyyy-MM-dd hh:mm:ss");
                // if (this.sendType == "图片") {
                //     var androidImgKey = "http://androidimg";
                //     msgbody.content = androidImgKey + msgbody.content;
                // }
                // console.log("发送的消息是",msgbody);
                this.messagelist.push(msgbody);
                this.message = "";


            } else {
                this.$message({
                    type: "warning",
                    message: "请输入内容",
                });
                // console.log("");
            }
        },
        //模拟发语音接收
        receiveSound() {
            //    this.messagelist.push({
            //         content:'/storage/emulated/0/Scj/Export/voice/20211224092214.amr',
            //         id:0,
            //         isread:0,
            //         issuccess:1,
            //         receiveid: 'local',
            //         sendid:this.chatObj.name,
            //         time:'2021-12-24 12:21:31',
            //         type:'语音'
            //     });

            $App.chatBroadcast("语音");
            setTimeout(() => {
                this.messagelist[this.messagelist.length - 1].isread = 1;
            }, 5000);
        },
        //模拟发图片接收
        receivePic() {
            this.messagelist.push({
                content: "aa",
                id: 0,
                isread: 0,
                issuccess: 1,
                receiveid: "local",
                sendid: "陈晨",
                time: "2021-12-24 12:22:31",
                type: "图片",
            });
            $App.chatBroadcast("图片");
            setTimeout(() => {
                this.messagelist[this.messagelist.length - 1].isread = 1;
            }, 3000);
        },
        //模拟文字接收
        onmessage(dt) {
            //判断isread，如果
            if (this.chatObj.id == dt.sendid) {
                $App.readChat(dt.sendid);
            }
            this.resciveMsg = dt;
            if (this.resciveMsg.type == "文字") {
                if (
                    this.resciveMsg.sendid == this.chatObj.id &&
                    this.resciveMsg.receiveid == "local"
                ) {
                    console.log("Receive" + JSON.stringify(this.messagelist));
                    this.messagelist.push(this.resciveMsg);
                    console.log("Receive" + JSON.stringify(this.messagelist));
                }
            } else if (this.resciveMsg.type == "语音") {
                if (
                    this.resciveMsg.sendid == this.chatObj.name &&
                    this.resciveMsg.receiveid == "local"
                ) {
                    this.messagelist.push(this.resciveMsg);
                }
            } else if (this.resciveMsg.type == "图片") {
                if (this.$route.path == "/chatinfo" && this.chatObj.name == dt.sendid) {
                    this.resciveMsg.isread = 1;
                    var androidImgKey = "http://androidimg";
                    this.resciveMsg.content = androidImgKey + this.resciveMsg.content;
                }
                setTimeout(() => {
                    this.messagelist.push(this.resciveMsg);
                }, 1000);
            }
        },
        onmessage2() {
        },
        //模拟
        show() {
            // //5s发文字
            setTimeout(() => {
                timecal.caldatetime(this.preTime, Date.now());
                // this.onmessage()
                //  this.receivePic();
            }, 5000);
            // //15s后发图片
            setTimeout(() => {
                // this.onmessage2()
            }, 15000);
            // //30s后发语音
            // setTimeout(() => {
            //     this.receiveSound()
            // },30000);

            // //10s后发语音
            // setTimeout(this.receivePic(),30000);
        },
        tobottom() {
            let messagebox = this.$refs.messagebox;
            if (messagebox.scrollHeight > messagebox.clientHeight) {
                messagebox.scrollTop = messagebox.scrollHeight;
            }
        },
        onRefresh() {
            setTimeout(() => {
                this.isLoading = false;
                this.count++;
            }, 1000);
        },
        backToAddress() {
            // this.$router.push("/chatlist");
            this.$router.push("/chatlist");
        },
        //时间转换函数
        dateTimeChange() {
            let datetime = new Date();
            let Y = datetime.getFullYear();
            let M =
                datetime.getMonth() + 1 < 10
                    ? "0" + (datetime.getMonth() + 1)
                    : datetime.getMonth() + 1;
            let D =
                datetime.getDate() < 10 ? "0" + datetime.getDate() : datetime.getDate();
            let h =
                datetime.getHours() < 10
                    ? "0" + datetime.getHours()
                    : datetime.getHours();
            let m =
                datetime.getMinutes() < 10
                    ? "0" + datetime.getMinutes()
                    : datetime.getMinutes();
            let s =
                datetime.getSeconds() < 10
                    ? "0" + datetime.getSeconds()
                    : datetime.getSeconds();
            return Y + "-" + M + "-" + D + " " + h + ":" + m + ":" + s;
        },
        dateTimeChange2(timeStr) {
            let datetime = new Date(timeStr);
            let Y = datetime.getFullYear();
            let M =
                datetime.getMonth() + 1 < 10
                    ? "0" + (datetime.getMonth() + 1)
                    : datetime.getMonth() + 1;
            let D =
                datetime.getDate() < 10 ? "0" + datetime.getDate() : datetime.getDate();
            let h =
                datetime.getHours() < 10
                    ? "0" + datetime.getHours()
                    : datetime.getHours();
            let m =
                datetime.getMinutes() < 10
                    ? "0" + datetime.getMinutes()
                    : datetime.getMinutes();
            let s =
                datetime.getSeconds() < 10
                    ? "0" + datetime.getSeconds()
                    : datetime.getSeconds();
            return Y + "-" + M + "-" + D + " " + h + ":" + m + ":" + s;
        },


    },
    mounted() {
        this.getDtfromRoute();
        window.recordStart = this.recordStart;
        window.recordEnd = this.recordEnd;
        //自主返回到上一页
        window.backToPrev = this.backToPrev;
        //关于图片的
        window.photoUpload = this.photoUpload;
        // 标识类，群聊还是私聊
        // window.getPageRoute = this.getPageRoute;
        bus.$on("onmessage", (dt) => {
            this.onmessage(dt);
            console.log("ChatInfo" + JSON.stringify(dt));
        });
    },
    updated() {
        this.tobottom();
    },
    watch: {
        socketMes: {
            deep: true,
            handler(newVal, oldVal) {
                // console.log("chatinf" + newVal)
                let socketContent = JSON.parse(JSON.parse(newVal).content)
                // console.log(new Date(Number(socketContent.SJ)))
                let timeStr = this.dateTimeChange2(socketContent.SJ);
                console.log(socketContent)
                let tmpObj = {
                    content: socketContent.NR,
                    fsbdid: "",
                    fsztmc: "",
                    receiveid: 'local',//标识是收到的还是发送的
                    jsbdid: socketContent.JSBDID,
                    jsztmc: socketContent.JSZTMC,
                    nr: socketContent.NR,
                    nrlx: socketContent.NRLX,
                    sj: timeStr,
                    time: timeStr,
                    type: socketContent.NRLX == 0 ? '文字' : socketContent.NRLX == 1 ? '高分' : "任务",
                }
                // console.log(tmpObj)
                this.messagelist.push(tmpObj)
            }
        }
    }

};
</script>
<style scoped>
.chart_container {
    height: 100%;
    width: 100%;
    display: flex;
    flex-direction: column;
}

.chart_container .header {
    background-color: #03192b;
    color: white;
}

/deep/.van-nav-bar .van-icon {
    color: white;
}

/deep/.van-nav-bar .van-nav-bar__title {
    color: white;
}

/deep/ .van-nav-bar .van-nav-bar__title {
    color: white;
}

/*聊天列表*/
.chatcontentbox {
    flex: 1;
    overflow-y: auto;
    position: relative;
    background-color: #f5f5f5;
}

/*聊天下部分*/
.chatinpubox {
    /*border: 1px solid rgba(21, 55, 68, 0.2);*/
    /*background-color: rgba(21, 55, 68, 0.11);*/
    /*display: flex;*/
    /*flex-direction: column;*/
    background-color: white;
    display: flex;
    align-items: center;
    height: 50px;
    padding: 0 10px;
}

.inputpart {
    /*height: 2.5rem;*/
    /*margin: 0.1rem 0;*/
    color: #999;
    display: flex;
    width: 100%;
    align-items: center;
}

.soundbtnbox {
    height: 100%;
    font-size: 1rem;
    display: flex;
    align-items: center;
    justify-content: center;
    width: 2rem;
}

.inputsoundmsg {
    margin: 0;
    flex: 1;
    height: 90%;
    text-align: center;
    border: 1px solid rgba(21, 55, 68, 0.2);
    line-height: 2rem;
}

.inputmsg {
    flex: 1;
    background-color: #f7f7f7;
    /*height: 95%;*/
    margin: 0;
    color: #bfbfbf;
    border: none;
    height: 35px;
}

.send_btn {
    width: 45px;
    height: 45px;
    background-image: url("../../assets/chat/发送拷贝.png");
    background-size: contain;
    background-repeat: no-repeat;
    margin-left: 10px;
    background-position-y: center;
}

/* .plusbox{
            flex:1;
        } */
.iconBtn {
    width: auto;
    height: 2rem;
}

.soundinputbox {
    height: 2.5rem;
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
}

.pressbtn {
    height: 2rem;
    width: 2rem;
    border: 1px solid #000;
    border-radius: 50%;
}

.otherbtnsbox {
    display: flex;
    /* height: 3rem; */
    height: 5rem;
    align-items: center;
    justify-content: space-around;
}

.otherbtnitem {
    display: flex;
    flex-direction: column;
    align-items: center;
}

.otherbtnimg {
    height: 2rem;
    border-radius: 0.2rem;
    width: 2rem;
    display: flex;
    align-items: center;
    justify-content: center;
}

.otherbtnText {
    line-height: 1rem;
    font-size: 0.7rem;
}
</style>

